/// <reference path="D:\src\jquery-1.8.1.js" />

var parameters = new Parameters("");
var dictionaire = new CollectionDictionary(parameters);
var idContentPanel = new String("#s4-workspace");

$(document).ready(function () { $(idContentPanel).hide(); });

function show() {
    $(idContentPanel).show().fadeIn('slow');
    resizeDialog();
}

var SPConfig = {
    errormsg: "",
    errorCancel: "",
    listCreated: "",
    listText: "",
    ListTitle: "",
    siteUrl: window.location.pathname,
    listCreated: false,
    h1DisplayList: "",
    count: 0,
    maxReturnItems: 0,
    ShowReplace: false,
    errormsgSameKeyword: ""
};

function setData(h1DisplayList, ListTitle, errormsg, errorCancel, listCreated, listText, maxReturnItems, errormsgSameKeyword) {
    SPConfig.errormsg = errormsg;
    SPConfig.errorCancel = errorCancel;
    SPConfig.listCreated = listCreated;
    SPConfig.listText = listText;
    SPConfig.ListTitle = ListTitle;
    SPConfig.h1DisplayList = h1DisplayList;
    SPConfig.maxReturnItems = maxReturnItems;
    SPConfig.errormsgSameKeyword = errormsgSameKeyword;
}

// set language from server
function setLanguages(langs) {
    SPFields.langs = langs;
}

var SPFields = {
    title: "Title",
    langs: new Array(),
    pageURL: "PageURL"
};

function RetrieveListItems(showReplace) {
    if (showReplace != undefined)
        SPConfig.ShowReplace = showReplace;

    //Create list using client OM
    checklistExist(SPConfig.ListTitle);
}

function GetCurrentLanguage() {
    return _spPageContextInfo.currentLanguage;
}

function ChangeOptionsFields(key, value) {
    $("select option").filter(function () {
        return $(this).val() == key;
    }).each(function () {
        $(this).text(value);
        $(this).val(key);
    });

    $("label").filter(function () {
        return $(this).text() == key;
    }).each(function () {
        $(this).text(value);
    });
}

function WriteLanguage() {
    var selector;

    for (index = 0; index < dictionaire.Collection.length; index++) {
        var key = dictionaire.Collection[index].keyword;

        //change option fields
        ChangeOptionsFields(key, dictionaire.Collection[index].langs[GetCurrentLanguage()]);

        // change all text
        if (dictionaire.elementID.toString() != "") {
            selector = "Body #" + dictionaire.elementID.toString() + " :contains('" + key + "')";
        }
        else {
            selector = "Body  :contains('" + key + "')";
        }
        var data = $(selector);
        if (data.length > 0) {
            var htmlData = data[data.length - 1].innerHTML;
            data[data.length - 1].innerHTML = replaceAll(htmlData, key, dictionaire.Collection[index].langs[GetCurrentLanguage()]);
        }

        for (i = 0; i < data.length - 1; i++) {
            var htmlData = data[i].innerHTML;
            if (data[i].firstChild != null) {
                if (!data[i].firstChild.hasChildNodes()) {
                    if (dictionaire.Collection[index].langs[GetCurrentLanguage()] != undefined && dictionaire.Collection[index].langs[GetCurrentLanguage()] != null && htmlData != "")
                        data[i].innerHTML = replaceAll(htmlData, key, dictionaire.Collection[index].langs[GetCurrentLanguage()]);
                }
            }
            else {
                if (dictionaire.Collection[index].langs[GetCurrentLanguage()] != undefined && dictionaire.Collection[index].langs[GetCurrentLanguage()] != null && htmlData != "")
                    data[i].innerHTML = replaceAll(htmlData, key, dictionaire.Collection[index].langs[GetCurrentLanguage()]);
            }
        }
    }
    show();
}

function resizeDialog() {
    if (SP.UI.ModalDialog.get_childDialog() != null && SP.UI.ModalDialog.get_childDialog() != undefined) {
        //calling autoSize method will extend modal dialog beyond the size of the page
        SP.UI.ModalDialog.get_childDialog().autoSize();
        //calling this obfuscated method will trim the dialog back within the page boundaries.
        SP.UI.ModalDialog.get_childDialog().$2B_0();
    }
}

function Parameters(elementID) {
    this.elementID = elementID;
}

function CollectionDictionary(params) {
    this.Collection = new Array();
    this.elementID = new String(params.elementID);
}

function Dictionary(keyword, langs, isGlobal) {
    this.keyword = new String(keyword);
    this.langs = langs;
    this.isGlobal = isGlobal;
}

function replaceAll(txt, replace, with_this) {
    return txt.replace(new RegExp("\\b" + replace + "\\b", "g"), with_this);
}

function AddDictionaryItem(frm) {
    var inputkeyword = frm.AddKeyword.value;

    var isGlobal = $('#global').is(':checked');
    var errorValidation = false;

    var langs = new Array();

    for (var i = SPFields.langs.length - 1; i >= 0; i--) {
        valueTextbox = $(":input[id$='" + SPFields.langs[i] + "']").val();

        if (valueTextbox.length > 2) {
            langs[SPFields.langs[i]] = valueTextbox;
        } else { errorValidation = true }
    }

    // need more than 2 char
    if (inputkeyword.length <= 2 && errorValidation != false) {
        alert(SPConfig.errormsg);
        return;
    }

    //new entry
    var myDict = new Dictionary(inputkeyword, langs, isGlobal);

    /// check if this keyword exist
    if (CheckIfKeywordExist(myDict) == true) {
        alert(SPConfig.errormsgSameKeyword);
        return;
    }

    //add
    AddNewEntry(myDict);
    //reset
    resetValues(frm);
    //show dictionary
    writeTableKeywords();
}

/// add my new entry to dictionary and sp list item
function AddNewEntry(myDict) {
    dictionaire.Collection.push(myDict);
    createListItem(myDict);
}

/// reset all value to blanck
function resetValues(frm) {
    frm.AddKeyword.value = "";
    for (var i = SPFields.langs.length - 1; i >= 0; i--) {
        valueTextbox = $(":input[id$='" + SPFields.langs[i] + "']").val("");
    }

    $('#global').attr('checked', false);
}

///Check if keyword exist into my dictionary
function CheckIfKeywordExist(myDict) {
    var length = dictionaire.Collection.length;

    for (var i = 0; i < length; i++) {
        currentKeyword = dictionaire.Collection[i].keyword;
        if (currentKeyword == myDict.keyword.toString())
            return true;
    }
    return false;
}

//Actual JS client side object model calls
function createList(listName) {
    if (SPConfig.listCreated == false) {
        //Create client context.
        var clientContext = new SP.ClientContext();
        var oWebsite = clientContext.get_web();
        var oList = oWebsite.get_lists().getByTitle(SPConfig.ListTitle);
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml('<View><RowLimit>' + SPConfig.maxReturnItems + '</RowLimit></View>');
        this.collListItem = oList.getItems(camlQuery);
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(
										Function.createDelegate(this, this.onCreateListLoadQuerySucceeded),
										Function.createDelegate(this, this.onCreateListLoadQueryFailed));

        //Let's create list creation information object
        var listCreationInfo = new SP.ListCreationInformation();
        listCreationInfo.set_title(listName);
        listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
        //not visible into the quick lunch
        listCreationInfo.set_quickLaunchOption(SP.QuickLaunchOptions.off);

        this.oList = oWebsite.get_lists().add(listCreationInfo);

        for (var i = SPFields.langs.length - 1; i >= 0; i--) {
            clientContext.load(addField(this, "lang_" + SPFields.langs[i]));
        }

        clientContext.load(addField(this, SPFields.pageURL));
        clientContext.load(oList);
        //Execute the actual script
        clientContext.executeQueryAsync(
										Function.createDelegate(this, this.onCreateListQuerySucceeded),
										Function.createDelegate(this, this.onCreateListQueryFailed));
    }
    else {
        if (SPConfig.count > 0)
            readListName(SPConfig.ShowReplace);
    }
}

function createListItem(dict) {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle(SPConfig.ListTitle);
    var itemCreateInfo = new SP.ListItemCreationInformation();

    this.oListItem = oList.addItem(itemCreateInfo);
    if (dict.keyword != null && dict.keyword != undefined)
        oListItem.set_item(SPFields.title, dict.keyword);
    for (var i = SPFields.langs.length - 1; i >= 0; i--) {
        if (dict.langs[SPFields.langs[i]] != null && dict.langs[SPFields.langs[i]] != undefined)
            oListItem.set_item("lang_" + SPFields.langs[i].toString(), dict.langs[SPFields.langs[i]]);
    }

    if (dict.isGlobal != true) {
        if (SPConfig.siteUrl != null && SPConfig.siteUrl != undefined)
            oListItem.set_item(SPFields.pageURL, SPConfig.siteUrl);
    }
    oListItem.update();
    clientContext.load(oListItem);
    clientContext.executeQueryAsync(
									Function.createDelegate(this, this.onQueryAddSucceeded),
									Function.createDelegate(this, this.onQueryAddFailed));
}

///////////////////////////////////////////
// Read List
///////////////////////////////////////////
function readListName(showReplace) {
    if (SPConfig.count > 0 || dictionaire.Collection.length > 0) {
        this.showReplace = showReplace;
        //Create client context.
        var clientContext = new SP.ClientContext();
        var oWebsite = clientContext.get_web();
        var oList = oWebsite.get_lists().getByTitle(SPConfig.ListTitle);
        var camlQuery = new SP.CamlQuery();
        //query
        var strQuery = '<View><Query><Where><Or><Eq><FieldRef Name="' + SPFields.pageURL + '" /><Value Type="Text">' +
							 SPConfig.siteUrl +
						   '</Value></Eq><IsNull><FieldRef Name="' + SPFields.pageURL + '" />' +
						   '</IsNull></Or></Where>' +
						   '<OrderBy><FieldRef Name="Title" Ascending="True" /></OrderBy></Query><RowLimit>' +
							SPConfig.maxReturnItems + '</RowLimit>' +
							'<ViewFields><FieldRef Name="Title" />';

        for (var i = SPFields.langs.length - 1; i >= 0; i--) {
            var f = 'lang_' + SPFields.langs[i];
            strQuery += '<FieldRef Name="' + f + '" />';
        }

        strQuery += '<FieldRef Name="' + SPFields.pageURL + '" />' +
							'</ViewFields></View>';

        camlQuery.set_viewXml(strQuery);
        this.collListItem = oList.getItems(camlQuery);
        //execute
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(
				Function.createDelegate(this, this.onReadListNameQueryReadSucceeded),
				Function.createDelegate(this, this.onReadListNameQueryReadFailed)
			);
    }
}

function onReadListNameQueryReadSucceeded(sender, args) {
    dictionaire = new CollectionDictionary(parameters);
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        // get page value
        var page = oListItem.get_item(SPFields.pageURL);

        //if no url then is global to site
        var isGlobal = (page == null);

        var langs = new Array();
        for (var i = SPFields.langs.length - 1; i >= 0; i--) {
            var f = "lang_" + SPFields.langs[i].toString();
            langs[SPFields.langs[i]] = oListItem.get_item(f);
        }

        //add
        dictionaire.Collection.push(new Dictionary(oListItem.get_item(SPFields.title),
														 langs, isGlobal));
    }
    writeTableKeywords();
}

//dispaly table (disctionary)
function writeTableKeywords() {
    $("#" + SPConfig.ListTitle).html("");
    var listItemCount = dictionaire.Collection.length;
    var s = "<br/><br/><h5>" + SPConfig.h1DisplayList + "</h5><hr /><table cellspacing ='5'>";
    for (var i = 0; i < listItemCount; i++) {
        var oDict = dictionaire.Collection[i];
        s += "<tr><th>Keyword</th> <td>" + oDict.keyword + ",</td>";
        "<td colspan='" + (SPFields.langs.length + 2) + "'";

        for (var j = SPFields.langs.length - 1; j >= 0; j--) {
            s += "<td>lang_" + SPFields.langs[j] + ":</td><td>" + oDict.langs[SPFields.langs[j]] + "</td> ";
        }
        s += "<td> IsGlobal :</td> <td >" + oDict.isGlobal + "</td></tr><tr><td colspan=" +
		(SPFields.langs.length + 4) + "></td></tr>";
    }

    if (this.showReplace) {
        WriteLanguage();
    }
    s += "</table><br/>";
    $("#" + SPConfig.ListTitle).html(s);

    show();
}

///////////////////////////////////////////
// Create LISt
///////////////////////////////////////////
function checklistExist(listName) {
    try {
        var clientContext = new SP.ClientContext();
        var oWebsite = clientContext.get_web();
        var oList = oWebsite.get_lists().getByTitle(listName);
        var camlQuery = new SP.CamlQuery();
        var strQuery = new String('<View><Query><Where><Or><Eq><FieldRef Name="' +
							 SPFields.pageURL +
							 '" /><Value Type="Text">' +
							 SPConfig.siteUrl +
						   '</Value></Eq><IsNull><FieldRef Name="' +
							SPFields.pageURL +
							'" />' +
						   '</IsNull></Or></Where></Query><RowLimit>' +
							SPConfig.maxReturnItems +
							'</RowLimit></View>');

        camlQuery.set_viewXml(strQuery);
        this.collListItem = oList.getItems(camlQuery);
        clientContext.load(this.collListItem);
        clientContext.executeQueryAsync(
						Function.createDelegate(this, this.onChecklistSucceeded),
						Function.createDelegate(this, this.onChecklistFailed));
    } catch (e) {
        ExecuteOrDelayUntilScriptLoaded(function () { RetrieveListItems(false); }, "sp.js")
    }
}

//Add field to list
function addField(o, name) {
    this.oField = o.oList.get_fields().addFieldAsXml(
				'<Field DisplayName=\'' + name + '\' Type=\'Text\' />',
				true,
				SP.AddFieldOptions.defaultValue
		);
    return oField
}

// add item to list Succeeded
function onQueryAddSucceeded() {
    alert('Item add: ' + oListItem.get_item('Title'));
}

// create list succeeded
function onCreateListQuerySucceeded() {
    SP.UI.Notify.addNotification(SPConfig.listText + " <b>" + oList.get_title() + "</b> " + SPConfig.listCreated, false, "", null);
    SPConfig.listCreated = true;
}

// list load succeeded
function onCreateListLoadQuerySucceeded() {
    SP.UI.Notify.addNotification(SPConfig.listText + " <b>" + oList.get_title() + "</b> " + SPConfig.listCreated, false, "", null);
    SPConfig.listCreated = true;
}

// read list is good
function onChecklistSucceeded(sender, args) {
    SPConfig.count = this.collListItem.get_count();
    if (SPConfig.count >= 0) {
        SPConfig.listCreated = true;
        readListName(SPConfig.ShowReplace);
    } else {
        SPConfig.listCreated = false;
        createList(SPConfig.ListTitle);
    }
}

// error on read list
function onChecklistFailed(sender, args) {
    SPConfig.listCreated = false;
    SPConfig.count = 0;
    createList(SPConfig.ListTitle);
}

function onCreateListLoadQueryFailed(sender, args) {
    SP.UI.Notify.addNotification(SPConfig.listText + " <b>" + oList.get_title() + "</b> " + SPConfig.listCreated, false, "", null);
}

// error create list
function onCreateListQueryFailed(sender, args) {
    SP.UI.Notify.addNotification(SPConfig.errorCancel, false, "", null);
}

function onReadListNameQueryReadFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

// error to add item
function onQueryAddFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}